package demo1;

/**
 * Created with IntelliJ IDEA
 * Description：使用类的clone,equals
 * User：chenshu
 * Date：2023-10-22
 * Time：09:55
 */

import java.util.Objects;

/**
 * 这个接口是一个空接口【标记接口】-》当前类是可以被克隆的
 */
/*public interface Cloneable {
}*/

class Money implements Cloneable{
    double money;

    public Money(double money) {
        this.money = money;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Money money1 = (Money) o;
        return Double.compare(money, money1.money) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(money);
    }
}
class Person implements Cloneable{
    public String id = "12021052019";
    Money m = new Money(19.99);

    public Person() {
        this("001", 99.99);
    }

    public Person(String id, double money) {
        this.id = id;
        m = new Money(money);
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        //深拷贝的实现
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;
        if (this.id .equals(person.id) && this.m.equals(person.m)) {
            return true;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, m);
    }
}
public class TestDemo {
    public static void main(String[] args) {
        Person[] people = new Person[3];
        people[0] = new Person("001", 9.9);
        people[1] = new Person("002", 19.9);
        people[2] = new Person("003", 29.9);

        //即使实现了Person类的深拷贝clone()，Person[]数组还是浅拷贝
        Person[] people1 = people.clone();
        people1[0].id = "1001";

        System.out.println(people[0].id);
    }
    public static void main1(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person();
        Person person2 = (Person)person1.clone();

        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
        System.out.println("=====================");
        person2.m.money = 99.99;
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);

        System.out.println("=====================");
        person2.m.money = 19.99;
        System.out.println(person1.equals(person2));
    }
}
